// 添加缺少的导入
import React, { useState, useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import './shi.css';
import axios from 'axios';

const VideoDetail = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { id } = useParams();
  const [video, setVideo] = useState(null);
  const [liked, setLiked] = useState(false);
  const [hasViewed, setHasViewed] = useState(false);
  const [comments, setComments] = useState([]);
  const [newComment, setNewComment] = useState('');
  const [danmaku, setDanmaku] = useState('');
  const [danmakus, setDanmakus] = useState([]);
  const videoRef = useRef(null);
  const danmakuContainerRef = useRef(null);

  const getVideoDetail = async () => {
    if (hasViewed) return;

    try {
      setLoading(true);
      const res = await axios.get(`http://localhost:3005/api/jjk/shi/${id}`);
      if (res.data && res.data.code === 200) {
        setVideo(res.data.data);
        setComments(res.data.data.comments || []);
        setHasViewed(true);
      } else {
        setError('获取视频失败: ' + (res.data?.msg || '未知错误'));
      }
    } catch (err) {
      setError('网络错误: ' + err.message);
      console.error('获取视频详情失败:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (id) {
      getVideoDetail();
    }
  }, [id]);

  const handleLike = async () => {
    if (liked || !video) return;

    try {
      const res = await axios.post(`http://localhost:3005/api/jjk/shi/${video._id}/like`);
      if (res.data.code === 200) {
        setVideo(prev => ({...prev, likes: res.data.data.likes}));
        setLiked(true);
      }
    } catch (err) {
      console.error('点赞失败:', err);
      alert('点赞失败: ' + (err.response?.data?.msg || err.message));
    }
  };

  const submitComment = async () => {
    if (!newComment.trim() || !video) return;

    try {
      const res = await axios.post(`http://localhost:3005/api/jjk/shi/${video._id}/comment`, {
        content: newComment
      });
      if (res.data.code === 200) {
        setComments([...comments, res.data.data]);
        setNewComment('');
      }
    } catch (err) {
      console.error('提交评论失败:', err);
      alert('提交评论失败: ' + (err.response?.data?.msg || err.message));
    }
  };

  const sendDanmaku = () => {
    if (!danmaku.trim()) return;

    const newDanmaku = {
      id: Date.now(),
      content: danmaku,
      color: getRandomColor(),
      position: Math.floor(Math.random() * 70) + 10, // 10-80% 垂直位置
      speed: Math.floor(Math.random() * 3) + 3, // 3-5秒
    };

    setDanmakus([...danmakus, newDanmaku]);
    setDanmaku('');

    // 3秒后移除弹幕
    setTimeout(() => {
      setDanmakus(prev => prev.filter(d => d.id !== newDanmaku.id));
    }, 8000);
  };

  const getRandomColor = () => {
    const colors = ['#FFFFFF', '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];
    return colors[Math.floor(Math.random() * colors.length)];
  };

  return (
    <div className="video-detail-container">
      <div className="video-player-wrapper">
        {loading ? (
          <div className="loading-state">加载中...</div>
        ) : error ? (
          <div className="error-state">错误: {error}</div>
        ) : !video ? (
          <div className="not-found-state">未找到该视频</div>
        ) : (
          <div key={video._id} className="video-item">
            <div className="video-container">
              <video 
                ref={videoRef}
                src={video.videourl}
                controls
                className="video-player"
                width="100%"
                height="auto"
                poster={video.cover}
                onError={(e) => {
                  console.error('视频加载错误:', e);
                  console.error('视频URL:', video.videourl);
                  alert('视频加载失败，URL: ' + video.videourl);
                }}
              >
                您的浏览器不支持视频播放
              </video>
              <div ref={danmakuContainerRef} className="danmaku-container"></div>
            </div>
            <div className="danmaku-input-container">
              <input
                type="text"
                value={danmaku}
                onChange={(e) => setDanmaku(e.target.value)}
                placeholder="发送弹幕..."
                className="danmaku-input"
                onKeyPress={(e) => e.key === 'Enter' && sendDanmaku()}
              />
              <button onClick={sendDanmaku} className="send-danmaku">发送</button>
            </div>
            <div className="video-info">
              <h1 className="video-title">{video.title}</h1>
              <div className="video-meta">
                <span className="video-views">{video.views}次观看</span>
                <span className="video-publish-date">发布于 {video.publishDate}</span>
                <button 
                  onClick={handleLike}
                  disabled={liked}
                  className={`like-button ${liked ? 'liked' : ''}`}
                >
                  {liked ? '已点赞' : '点赞'} {video.likes || 0}
                </button>
              </div>
              <div className="video-description">
                <p>{video.description}</p>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="content-container">
        {/* 评论区 */}
        <div className="comments-section">
          <h2>评论 ({comments.length})</h2>
          <div className="comment-input-container">
            <input
              type="text"
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
              placeholder="写下您的评论..."
              className="comment-input"
              onKeyPress={(e) => e.key === 'Enter' && submitComment()}
            />
            <button onClick={submitComment} className="send-comment">发送</button>
          </div>
          <div className="comments-list">
            {comments.map(comment => (
              <div key={comment._id || comment.id} className="comment-item">
                <img src={comment.avatar || 'https://picsum.photos/id/64/40/40'} alt={comment.user} className="comment-avatar" />
                <div className="comment-content">
                  <div className="comment-header">
                    <span className="comment-user">{comment.user || '匿名用户'}</span>
                    <span className="comment-time">{comment.time || new Date().toLocaleDateString()}</span>
                  </div>
                  <p className="comment-text">{comment.content}</p>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 相关视频 - 增加额外的空值检查 */}
        <div className="related-uploads">
          <h2>相关视频</h2>
          <div className="related-uploads-grid">
            {video && (video.relatedVideos || []).map(related => (
              <div key={related._id} className="related-video-item">
                <img 
                  src={related.cover || '默认封面图片路径'} 
                  alt={related.title} 
                  className="related-video-cover"
                />
                <div className="related-video-info">
                  <h3 className="related-video-title">{related.title}</h3>
                  <div className="related-video-meta">
                    <span className="related-video-views">{related.views}次观看</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default VideoDetail;
